package cn.jhc.social.qq.api.impl;

import java.util.List;

import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;
import org.springframework.social.support.ClientHttpRequestFactorySelector;
import org.springframework.web.client.RestTemplate;

import cn.jhc.social.qq.api.QQ;
import cn.jhc.social.qq.api.UserOperations;
import cn.jhc.social.qq.api.impl.json.QQModule;

import com.fasterxml.jackson.databind.ObjectMapper;

public class QQTemplate extends AbstractOAuth2ApiBinding implements QQ {
	
	private UserOperations userOperations;
	private String consumerKey;
	private String openid = null;

	public QQTemplate(String accessToken, String consumerKey) {
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
		// Wrap the request factory with a BufferingClientHttpRequestFactory so that the error handler can do repeat reads on the response.getBody()
		super.setRequestFactory(ClientHttpRequestFactorySelector.bufferRequests(getRestTemplate().getRequestFactory()));
		
		this.consumerKey = consumerKey;
		addConsumerKey(getRestTemplate());
		userOperations = new UserTemplate(this, isAuthorized());
	}

	
	
	protected RestTemplate addConsumerKey(RestTemplate restTemplate) {
		super.configureRestTemplate(restTemplate);
		List<ClientHttpRequestInterceptor> intercepters = restTemplate.getInterceptors();
		intercepters.add(new ConsumerKeyRequestIntercepter(consumerKey));
		restTemplate.setInterceptors(intercepters);
		return restTemplate;
	}

	@Override
	public UserOperations userOperations() {
		return userOperations;
	}
	
	@Override
	public void setRequestFactory(ClientHttpRequestFactory requestFactory) {
		// Wrap the request factory with a BufferingClientHttpRequestFactory so that the error handler can do repeat reads on the response.getBody()
		super.setRequestFactory(ClientHttpRequestFactorySelector.bufferRequests(requestFactory));
	}
	
	@Override
	protected MappingJackson2HttpMessageConverter getJsonMessageConverter() {
		MappingJackson2HttpMessageConverter converter = new HTMLMappingJackson2HttpMessageConverter();
		converter.setObjectMapper(new ObjectMapper().registerModule(new QQModule()));
		return converter;
	}

	@Override
	public String getOpenid() {
		if(openid == null)
			openid = new OpenidTemplate(getRestTemplate(),isAuthorized()).getOpenid(); 
		return openid;
	}

}